# ------------------------------------------------------------------------------------------------
### Shared functions for table generation
# ------------------------------------------------------------------------------------------------

## Common filtering function for SDID results
filter_sdid_results <- function(data, outcome_filter = NULL, party_filter = NULL, 
                               sum_level_filter = "Any Level", sum_type_filter = "Any Type",
                               level_filter = "Any Level", type_filter = "Any Type",
                               control_sample_filter = "notyettreated",
                               no300k_sample_filter = "Full Sample",
                               noproposed_sample_filter = "Full Sample") {
  
  data %>%
    filter(
      if (!is.null(outcome_filter)) outcome %in% outcome_filter else TRUE,
      if (!is.null(party_filter)) party %in% party_filter else TRUE,
      sum_level == sum_level_filter,
      sum_type == sum_type_filter,
      level == level_filter,
      type == type_filter,
      control_sample == control_sample_filter,
      no300k_sample == no300k_sample_filter,
      noproposed_sample == noproposed_sample_filter
    )
}

## Function to create LaTeX table with common structure
create_latex_table <- function(data, group_var, row_var, caption, label, 
                              col_names = c("Group", "Sample", "Estimate (SE)", "N"),
                              add_spacing = TRUE) {
  
  # Build LaTeX table
  latex_parts <- c(
    "\\begin{table}[ht]",
    "\\centering",
    "\\begin{tabular}{llcc}",
    "\\hline\\hline",
    paste(paste(col_names, collapse = " & "), "\\\\"),
    "\\hline"
  )
  
  # Group data and generate rows
  grouped_data <- split(data, data[[group_var]])
  
  for (group_name in names(grouped_data)) {
    if (add_spacing) latex_parts <- c(latex_parts, "\\addlinespace")
    
    group_rows <- grouped_data[[group_name]]
    first_row <- TRUE
    group_label <- group_name
    
    for (i in 1:nrow(group_rows)) {
      row <- group_rows[i, ]
      
      if (first_row) {
        latex_parts <- c(latex_parts, 
          paste0(group_label, " & ", row[[row_var]], " & ", 
                 sprintf("%.2f", row$estimate), " & ", row$n_obs, " \\\\ & & (",
                 sprintf("%.2f", row$se), ") & \\\\"))
        first_row <- FALSE
      } else {
        latex_parts <- c(latex_parts,
          paste0(" & ", row[[row_var]], " & ", 
                 sprintf("%.2f", row$estimate), " & ", row$n_obs, " \\\\ & & (",
                 sprintf("%.2f", row$se), ") & \\\\"))
      }
    }
    
    if (add_spacing) latex_parts <- c(latex_parts, "\\addlinespace")
  }
  
  # Close table
  latex_parts <- c(latex_parts,
    "\\hline",
    "\\end{tabular}",
    paste0("\\caption{", caption, "}"),
    paste0("\\label{", label, "}"),
    "\\end{table}"
  )
  
  return(latex_parts)
}

## Function to create LaTeX table with sections (like table3)
create_sectioned_latex_table <- function(data, group_var, row_var, section_var, 
                                       caption, label, col_names = c("Group", "Sample", "Estimate (SE)", "N")) {
  
  latex_parts <- c(
    "\\begin{table}[ht]",
    "\\centering",
    "\\begin{tabular}{llcc}",
    "\\hline\\hline",
    paste(paste(col_names, collapse = " & "), "\\\\"),
    "\\hline"
  )
  
  # Process each section
  sections <- unique(data[[section_var]])
  
  for (section in sections) {
    section_data <- data %>% filter(!!sym(section_var) == section)
    
    # Add section header
    latex_parts <- c(latex_parts,
      "\\hline",
      paste0("\\multicolumn{4}{c}{\\textit{", section, "}} \\\\"),
      "\\hline",
      "\\addlinespace"
    )
    
    # Group by the main grouping variable within this section
    grouped_data <- split(section_data, section_data[[group_var]])
    
    for (group_name in names(grouped_data)) {
      group_rows <- grouped_data[[group_name]]
      first_row <- TRUE
      
      for (i in 1:nrow(group_rows)) {
        row <- group_rows[i, ]
        
        if (first_row) {
          latex_parts <- c(latex_parts,
            paste0(row[[group_var]], " & ", row[[row_var]], " & ", 
                   sprintf("%.2f", row$estimate), " & ", row$n_obs, " \\\\ & & (",
                   sprintf("%.2f", row$se), ") & \\\\"))
          first_row <- FALSE
        } else {
          latex_parts <- c(latex_parts,
            paste0(" & ", row[[row_var]], " & ", 
                   sprintf("%.2f", row$estimate), " & ", row$n_obs, " \\\\ & & (",
                   sprintf("%.2f", row$se), ") & \\\\"))
        }
      }
      latex_parts <- c(latex_parts, "\\addlinespace")
    }
  }
  
  # Close table
  latex_parts <- c(latex_parts,
    "\\hline",
    "\\end{tabular}",
    paste0("\\caption{", caption, "}"),
    paste0("\\label{", label, "}"),
    "\\end{table}"
  )
  
  return(latex_parts)
}

## Function to save table
save_table <- function(latex_content, output_path) {
  writeLines(latex_content, output_path)
}
